package org.fast.easy.auth.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.fast.easy.auth.domain.vo.LoginTenantVo;
import org.fast.easy.auth.domain.vo.LoginVo;
import org.fast.easy.auth.domain.vo.TenantListVo;
import org.fast.easy.auth.service.IAuthStrategy;
import org.fast.easy.auth.service.ISysLoginService;
import org.fast.easy.auth.service.SysLoginService;
import org.fast.easy.auth.util.LoginTenantUtil;
import org.fast.easy.common.i18n.util.MessageUtils;
import org.fast.easy.common.json.utils.JsonUtils;
import org.fast.easy.core.constant.UserConstants;
import org.fast.easy.core.domain.auth.form.RegisterBody;
import org.fast.easy.core.domain.auth.model.LoginBody;
import org.fast.easy.core.domain.result.R;
import org.fast.easy.core.util.StringUtils;
import org.fast.easy.core.util.ValidatorUtils;
import org.fast.easy.framework.encrypt.annotation.ApiEncrypt;
import org.fast.easy.framework.satoken.utils.LoginHelper;
import org.fast.easy.framework.tenant.helper.TenantHelper;
import org.fast.easy.messages.service.IMessageService;
import org.fast.easy.system.client.domain.vo.SysClientVo;
import org.fast.easy.system.client.service.ISysClientService;
import org.fast.easy.system.core.service.ISysConfigService;
import org.fast.easy.system.upms.domain.vo.SysTenantVo;
import org.fast.easy.system.upms.service.ISysSocialService;
import org.fast.easy.system.upms.service.ISysTenantService;
import org.springframework.web.bind.annotation.*;

import java.net.URL;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * token 控制
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class RemoteTokenController {

    private final ISysLoginService sysLoginService;

    private final ISysClientService sysClientService;
    private final ISysSocialService sysSocialService;
    private final ISysTenantService sysTenantService;
    private final ISysConfigService sysConfigService;

    private final IMessageService messageService;

    private final ScheduledExecutorService scheduledExecutorService;


    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @ApiEncrypt
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody String body) {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        SysClientVo clientVo = sysClientService.queryByClientId(clientId);

        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(clientVo) || !StringUtils.contains(clientVo.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!UserConstants.NORMAL.equals(clientVo.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        sysLoginService.checkTenant(loginBody.getTenantId());
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, clientVo, grantType);

        Long userId = LoginHelper.getUserId();
        scheduledExecutorService.schedule(() -> {
            try {
                messageService.sendMessage(userId, "欢迎登录SaaS微服务管理系统");
            } catch (Exception ignored) {
            }
        }, 3, TimeUnit.SECONDS);
        return R.ok(loginVo);
    }




    /**
     * 取消授权
     *
     * @param socialId socialId
     */
    @DeleteMapping(value = "/unlock/{socialId}")
    public R<Void> unlockSocial(@PathVariable Long socialId) {
        Boolean rows = sysSocialService.deleteWithValidById(socialId);
        return rows ? R.ok() : R.fail("取消授权失败");
    }


    /**
     * 用户注册
     */
    @ApiEncrypt
    @PostMapping("register")
    public R<Void> register(@RequestBody RegisterBody registerBody) {
        if (!sysConfigService.selectRegisterEnabled(registerBody.getTenantId())) {
            return R.fail("当前系统没有开启注册功能！");
        }
        // 用户注册
        sysLoginService.register(registerBody);
        return R.ok();
    }

    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @GetMapping("/tenant/list")
    public R<LoginTenantVo> tenantList(HttpServletRequest request) throws Exception {
        List<SysTenantVo> tenantList = sysTenantService.queryList(null);
        return R.ok(LoginTenantUtil.getLoginTenantVo(request,tenantList));
    }




}
